package biz.datalk.industrialland.common.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author tarofang@163.com
 * @date 2019-11-10
 */
public class SignUtil {

    public static Map<String, Object> sortMapObj(Map<String, Object> params) {
        return new TreeMap<String, Object>(params);
    }
    public static Map<String, String> sortMap(Map<String, String> params) {
        return new TreeMap<String, String>(params);
    }

    public static String genSignStr(Map<String, String> sortParams, String... excluedKeys) {
        if (MapUtils.isEmpty(sortParams)) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortParams.entrySet()) {
            String key = entry.getKey();
            String value =  entry.getValue();
            if (ArrayUtils.contains(excluedKeys, key)) {
                continue;
            }

            sb.append("&").append(key).append("=").append(value);
        }
        return sb.toString().replaceFirst("&", "");
    }

    public static boolean checkSign(String genSignStr, String sign) {
        String resMd5 = DigestUtils.md5Hex(genSignStr).toUpperCase();
        return StringUtils.equals(resMd5, sign);
    }

    public static boolean checkSign(String sign, Map<String, String> params, String... excluedKeys) {
        Map<String, String> sortMap = sortMap(params);
        String signStr = genSignStr(sortMap, excluedKeys);
        return checkSign(signStr, sign);
    }
}
